﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using LCA.Data;
using Composite.Data;
using System.Data.Linq.SqlClient;
using LCA.Utils;
using System.Transactions;
using Composite.Data.Transactions;

public partial class Admin_LCAFlow_Controls_FlowList : System.Web.UI.UserControl, LCA.Web.Controls.IPageableControl
{
    private int totalItems;
    private bool? boundAllowPaging;
    private int? boundPageSize;
    private int? boundPageIndex;

    public FlowSearchParameters? SearchParameters
    {
        get { return (FlowSearchParameters?)ViewState["FlowSearchParameters"]; }
        set { ViewState["FlowSearchParameters"] = value; }
    }

    private int? PageIndex
    {
        get { return (int?)ViewState["PageIndex"]; }
        set { ViewState["PageIndex"] = value; }
    }

    private bool WasInitialized
    {
        get
        {
            object wasInitialized = ViewState["WasInitialized"];
            return wasInitialized == null ? false : (bool)wasInitialized;
        }
        set
        {
            ViewState["WasInitialized"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack || !WasInitialized)
        {
            RefreshComponents();
        }
    }

    public void RefreshComponents()
    {
        if (this.Visible == false)
            return;

        if (this.SearchParameters == null)
            return;

        chkSelectAll.Checked = false;

        BindDataList();

        WasInitialized = true;
    }

    public int GetItemCount()
    {
        return totalItems;
    }

    public void ChangePageIndex(int pageIndex)
    {
        this.PageIndex = pageIndex;

        BindDataList();
    }

    private void BindDataList()
    {
        if (grdData.AllowPaging && grdData.AllowPaging == boundAllowPaging)
        {
            return;
        }
        if (!grdData.AllowPaging && this.PageIndex == boundPageIndex && grdData.PageSize == boundPageSize)
        {
            return;
        }

        using (DataConnection conn = new DataConnection())
        {
            var results = from flow in conn.Get<LCA.Data.Flow>()
                          where flow.IsDeleted == false
                          select new
                          {
                              Id = flow.Id,
                              Name = flow.Name
                          };

            if (SearchParameters != null)
            {
                if (!String.IsNullOrEmpty(SearchParameters.Value.Name))
                {
                    results = results.Where(x => SqlMethods.Like(x.Name, "%" + SearchParameters.Value.Name + "%"));
                }
            }

            if (!String.IsNullOrEmpty(grdSortExtender.SortExpression))
            {
                bool isAscending = grdSortExtender.SortDirection != SortDirection.Descending;
                switch (grdSortExtender.SortExpression)
                {
                    case "Name":
                        results = results.OrderBy(x => x.Name, isAscending);
                        break;

                }
            }
            else
            {
                results = results.OrderBy(x => x.Name, false);
            }

            totalItems = results.Count();
            litRecordCount.Text = totalItems.ToString();

            if (grdData.AllowPaging)
            {
                results = results.Skip(this.PageIndex.GetValueOrDefault() * grdData.PageSize);
                results = results.Take(grdData.PageSize);
            }

            grdData.DataSource = results.ToList();
            grdData.DataBind();

            boundPageIndex = this.PageIndex;
            boundPageSize = grdData.PageSize;
            boundAllowPaging = grdData.AllowPaging;
        }
    }

    public void ChangePageSize(int? pageSize)
    {
        if (pageSize == null)
        {
            grdData.AllowPaging = false;
        }
        else
        {
            grdData.AllowPaging = true;
            grdData.PageSize = pageSize.Value;
        }

        BindDataList();
    }

    public IList<Guid> GetSelectedIds()
    {
        IList<Guid> selectedIds = new List<Guid>();

        foreach (GridViewRow row in grdData.Rows)
        {
            CheckBox chkSelect = (CheckBox)row.FindControl("chkSelect");
            if (chkSelect.Checked)
            {
                Guid eventId = (Guid)grdData.DataKeys[row.RowIndex].Value;
                selectedIds.Add(eventId);
            }
        }

        return selectedIds;
    }

    protected void grdData_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            //dynamic obj = e.Row.DataItem;
            //Literal litIsTaxExempt = (Literal)e.Row.FindControl("litIsTaxExempt");
            //Literal litRequireCECredit = (Literal)e.Row.FindControl("litRequireCECredit");
            //litIsTaxExempt.Text = obj.IsTaxExempt.ToString();
            //litRequireCECredit.Text = obj.RequireCECredit.ToString();

            //Literal litSector = (Literal)e.Row.FindControl("litSector");
            //Literal litSectorType = (Literal)e.Row.FindControl("litSectorType");
            //Literal litSpecialty = (Literal)e.Row.FindControl("litSpecialty");
            //if (obj.SectorPlanSponsor != null)
            //{
            //    litSector.Text = "Plan Sponsor";
            //    litSectorType.Text = ((string)obj.SectorPlanSponsorType).HtmlEncode();
            //    litSpecialty.Text = ((string)obj.SectorSpecialtyType).HtmlEncode();
            //}
            //else if (obj.SectorProvider != null)
            //{
            //    litSector.Text = "Provider";
            //    litSectorType.Text = ((string)obj.SectorProviderType).HtmlEncode();
            //}
            //else
            //{
            //    litSector.Text = "Other";
            //    litSectorType.Text = ((string)obj.SectorOther).HtmlEncode();
            //}

            //Literal litPreferredLanguage = (Literal)e.Row.FindControl("litPreferredLanguage");
            //litPreferredLanguage.Text = obj.PreferredLanguageEn ? "English" : "French";

            //Button btnResetPassword = (Button)e.Row.FindControl("btnResetPassword");
            //btnResetPassword.CommandArgument = obj.Id.ToString();
        }
    }

    protected void grdData_RowEditing(object sender, GridViewEditEventArgs e)
    {
        Guid flowId = (Guid)grdData.DataKeys[e.NewEditIndex].Value;

        PageHelper.AdminPageRedirect(Page, "UpdateFlow.aspx?flowId=" + flowId);


    }

    protected void grdData_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        Guid flowId = (Guid)grdData.DataKeys[e.RowIndex].Value;

        using (TransactionScope transactionScope = TransactionsFacade.CreateNewScope())
        {
            using (DataConnection connection = new DataConnection())
            {
                var flow = connection.Get<LCA.Data.Flow>().Where(f => f.Id == flowId).FirstOrDefault();
                flow.IsDeleted = true;

                connection.Update<LCA.Data.Flow>(flow);

                //var flowFactors = connection.Get<LCA.Data.FlowFactor>().Where(ff => ff.Flow == flowId);
                //foreach (LCA.Data.FlowFactor factor in flowFactors)
                //{
                //    factor.IsDeleted = true;
                //    connection.Update<LCA.Data.FlowFactor>(factor);
                //}

                
            }

            transactionScope.Complete();
        }

        BindDataList();

        //OnDataDeleted(new EventArgs());
    }

    protected void grdData_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "Command")
        {

        }
    }

    protected void grdData_Sorting(object sender, GridViewSortEventArgs e)
    {
        if (e.SortExpression != grdSortExtender.SortExpression)
        {
            grdSortExtender.SortDirection = SortDirection.Ascending;
        }
        else
        {
            grdSortExtender.SortDirection = grdSortExtender.SortDirection == SortDirection.Ascending ? SortDirection.Descending : SortDirection.Ascending;
        }
        grdSortExtender.SortExpression = e.SortExpression;

        BindDataList();
    }
}